package com.ykh.mybbsdemo.service;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ykh.mybbsdemo.dao.mapper.ArticleMapper;
import com.ykh.mybbsdemo.dao.pojo.po.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-09-01
 * Time: 15:58
 */
@Service
//用于 执行对阅读数量的更新操作
public class ThreadService {

    @Async("taskExecutor")
    //期望 更新操作在线程池运行, 不影响到主线程
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {

        //执行更新阅读数量的操作
        //获取当前文章的阅读数
        Long viewCounts = article.getViewCounts();
        //创建一个新的文章对象,并更新其阅读数
        // 因为articleMapper.update()方法参数需要一整个对象, 而重新new一个对象,只修改其中的阅读数,有助于减少操作数
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts + 1);
        //创建更新的条件语句
        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Article::getId,article.getId());
        //为了在多线程环境下,线程安全
        updateWrapper.eq(Article::getViewCounts,viewCounts);

        //执行更新操作
        articleMapper.update(articleUpdate,updateWrapper);
        //对应的sql : update article set view_count=100 where view_count = 99 and id = 11;

        try {
            Thread.sleep(3000);
            System.out.println("更新完成!");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
